package com.huanbao.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.base.dto.VolunteerApplyCheckDTO;
import com.huanbao.base.lang.Result;
import com.huanbao.entity.*;
import com.huanbao.service.*;
import com.huanbao.util.ShiroUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 日常投放记录表 前端控制器
 * </p>
 *
 * @author zq
 * @since 2021-05-07
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdminController {

    private final DailyDeliveryRecordService deliveryRecordService;

    private final ShoppingMallService shoppingMallService;

    private final PersonalIntegralNumberService integralNumberService;

    private final PersonalNotificationService personalNotificationService;

    private final PersonalTaskService personalTaskService;

    private final VolunteerApplyService volunteerApplyService;

    private final UserService userService;

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 所有人最新一天的巡检记录
     * @return list
     */
    @GetMapping("/deliveryList")
    public Result deliveryList() {
        List<DailyDeliveryRecord> list = deliveryRecordService.list(new QueryWrapper<DailyDeliveryRecord>().ge("updated_dt",LocalDateTime.now().format(formatter)).isNull("score"));
        return Result.success(list);
    }

    /**
     * 日常监察打分
     *
     * @param recordId 打分id
     * @param score 分数
     * @return 200
     */
    @GetMapping("/recordModify/{record}/{score}")
    @RequiresAuthentication
    public Result recordModify(@PathVariable("record")Long recordId, @PathVariable("score") String score) {
        DailyDeliveryRecord deliveryRecord = deliveryRecordService.getById(recordId);
        deliveryRecord.setScore(score);
        if (!score.equals("差")) {
            deliveryRecord.setContinusousDays(deliveryRecord.getContinusousDays() + 1);
            //连续打卡七天加50积分
            if (deliveryRecord.getContinusousDays() >= 7) {
                PersonalIntegralNumber one = integralNumberService.getOne(new QueryWrapper<PersonalIntegralNumber>().eq("user_id", deliveryRecord.getUserId()));
                one.setIntegralNumber(one.getIntegralNumber() + 50);
                integralNumberService.updateById(one);
            }
        } else {
            deliveryRecord.setContinusousDays(deliveryRecord.getContinusousDays() - 1);
        }
        PersonalNotification notification = new PersonalNotification();
        notification.setContent(deliveryRecord.getCreatedDt().format(formatter) + "投放" + score)
                .setUserId(deliveryRecord.getUserId())
                .setPublisher(ShiroUtil.getProfile().getUsername());
        personalNotificationService.save(notification);
        deliveryRecordService.updateById(deliveryRecord);
        return Result.success(null);
    }

    /**
     * 商品列表全属性展示
     *
     * @return null
     */
    @GetMapping("/shoppingList")
    public Result shoppingList() {
        List<ShoppingMall> list = shoppingMallService.list();
        return Result.success(list);
    }

    @GetMapping("/shoppingOne/{id}")
    public Result shoppingOne(@PathVariable("id") Long id) {
        ShoppingMall byId = shoppingMallService.getById(id);
        return Result.success(byId);
    }

    /**
     * 修改或新增商品
     *
     * @param shoppingMall 商品实例
     * @return null
     */
    @PostMapping("/shopping/modify")
    public Result shoppingModify(@RequestBody ShoppingMall shoppingMall) {
        if (null != shoppingMall.getId()) {
            shoppingMallService.updateById(shoppingMall);
        } else {
            shoppingMallService.save(shoppingMall);
        }
        return Result.success(shoppingMall.getItemName());
    }

    @GetMapping("/volunteerApply")
    public Result voluntaryApply(){
        List<VolunteerApply> volunteerApplyList = volunteerApplyService.list(new QueryWrapper<VolunteerApply>().eq("state", 0));
        return Result.success(volunteerApplyList);
    }

    @RequiresAuthentication
    @PostMapping("/volunteerApply/check")
    public Result voluntaryApplyCheck(@RequestBody @Validated VolunteerApplyCheckDTO checkDTO){
        if (checkDTO.getResult() != 1 && checkDTO.getResult() != 2){
            return Result.fail("审核结果信息不正确，请核对");
        }
        volunteerApplyService.check(checkDTO);
        return Result.success(null);
    }

    @RequiresAuthentication
    @PostMapping("/volunteerTask/Release")
    public Result volunteerTaskRelease(@RequestBody PersonalTask task){
        personalTaskService.save(task);
        return Result.success(null);
    }


}
